﻿// JavaScript Document
//tab
 $(function(){
	if(!window.localStorage){
		new UserPrompt('您所使用的浏览器版本太低，或不支持本页面，请更换浏览器并重试！');
	}else{
	    var search = decodeURI(window.location.search.substr(1)),
	    key=matchQueryString(search,'sms'),
	    sms = localCache.getSessionItem(key),	
	    jsms = JSON.parse(sms),
	    _ttsInput = jsms.tts,
	    
	    calleeNumbers=[],
	    callerNum=jsms.data[0].telephone, //主叫
	    detailUrl = localCache.getSessionItem('sms_detail_url'),//查询语音通知发送明细
	    content = $('#detail');
	    localCache.removeSessionItem(key);
	
	    //返回事件
	    $('#back').on('click',function(){
	      history.back();
	    });
	
	    //发送语音通知接口
	    var sendVoiceNoticeLetUrl = localCache.getSessionItem("sendVoiceNoticeLet_url");
	    //账号标识
	    var account_identify = localCache.getSessionItem("account_identify");
	    //时间戳
	    var timestamp = localCache.getSessionItem("timestamp");
	    //加密串
	    var sign = localCache.getSessionItem("sign");
	    //用户id
	    var userId = localCache.getSessionItem("userId");
        //应用标识
        var appKey = localCache.getSessionItem("account_identifer");
	    //发送失败的手机号
	    var failedNumbers = []; 
	    //扩展indexOf获取Array中元素的索引值
	    Array.prototype.indexOf = function(el){
		    for (var i=0,n=this.length; i<n; i++){
			    if (this[i] === el){
			    	return i;
			    }
		    }
		    return -1;
	    }
	    
	    //------------------------发送状态html start-----------------------------
        var initContent = function(voiceId, telephone, name) {
        	$.ajax({
	            type: "get",
	            url: detailUrl,
	            dataType: "json",  
	            data:{
	            	voiceId: voiceId,
	            	telephone: telephone
	            },
	            async: true,
	            success: function(json){
	              if(json.result == 0){
	                var times = json.data.times;
	                var callState = json.data.callState;
	                var reason = json.data.reason;
	                if(callState != 'FAILED' && times > 0){
	                	content.append('<li><b>'+name+'</b><span>'+'发送成功	' + times + '\"'+'</span></li>');
	                }else if(callState != 'FAILED' && times == 0){
	                	content.append('<li><b>'+name+'</b><span>发送中...</span></li>');			
	                }else{
	                	content.append('<li><b>'+name+'</b><span id="' + telephone + '">发送失败(' + reason + ')</span><i id="' + telephone + '_i" style="display:block;"></i></li>');
	                	failedNumbers.push(telephone); //呼叫失败的号码
	                }
	              }else{
	            	  content.addClass('noresult').html('暂无记录'); 
	              }
	              if(jsms.data.length===$('.status li').length+1){   
			      	  //绑定重发事件
			      	  setTimeout(function(){
			      		bindEvent(); 
			      	  },0);  
	              }                			
	            },
	            error: function(){
	            	alert("error");
	            }
        	});
        };
	    //------------------------发送状态html end-----------------------------
        
	    //初始化数据
        $('.content').text(_ttsInput);
        $('.time').text(formatDateTime(jsms.time));
	    sessionIdArray = jsms.sessionArray;
	    for(var i=0;i<jsms.data.length;i++){ //i=0是主持人的号码
	    	var _telephone = jsms.data[i].telephone;
	    	var _name = jsms.data[i].name;
	    	var sessionId = sessionIdArray[_telephone];
	    	if(i == 0){ //主叫号码
	    		callerNum = _telephone;
	    	}else{
	    		calleeNumbers.push(_telephone);//被叫
	    		initContent(sessionId, _telephone, _name); 
	    	}
	    };
	    
	    	    
	    //------------------重新发送start---------------------
	    var reSend = function(calleeNumber){
	    	var _voiceId = jsms.sessionArray[calleeNumber];
            $.ajax({
                type: "get",
                dataType: "json",
                url: sendVoiceNoticeLetUrl,
                async: true,
                data: {
                	'app_key': appKey,
                    'cust_account': account_identify,
                    'caller': callerNum,
                    'ext_terminalCode': userId,
                    'called': calleeNumber,
                    'timestamp': timestamp,
                    'sign': sign,
                    'schedule_send_time':'',
                    'voice_id': _voiceId,
                    'tts_content': _ttsInput
                },
				beforeSend:function(){
					loadPrompt=new LoadPrompt('发送中...');
				},
                success: function (json) {
                    if (json['result'] == '0') {
                    	//呼叫失败的号码
                    	failedNumbers.splice( failedNumbers.indexOf(calleeNumber), 1); 
                    	//更新发送状态
                    	var _span = '#'+calleeNumber;
                    	$(_span).text("发送中...");
                    	//隐藏重发按钮
                    	var _i = '#'+calleeNumber+'_i';
                    	$(_i)[0].style.display = "none"; 
                        //更新缓存数据
                    	meetCache.updateMeetInfo(jsms.session_id, json.voice_id);
                    } else {
                        new UserPrompt(json['describe']+"请稍后再试！");  
                    }
                },
                error: function (json) {
                    new UserPrompt("连接异常，请稍后再试！");
                },
                complete: function () {
					if(loadPrompt){
						loadPrompt.close();
						loadPrompt=null;
					}
                }
            });
	    }
	    //-------------------------重新发送end------------------------------

	    //-------------------------绑定重发事件 begin-------------------------
	    var bindEvent = function(){ 
	    	$('.status li').each(function(i,elem) {
			    var callee=$(this); 
			    var number=callee.find('span').attr('id'); 
			    if(number){   
				    callee.find('i').on('click',function(){
		            	reSend(number); //重发   
		            });
			    }
	    	});
	    };
	    //------------------绑定重发事件 end---------------------------------
	    
        //------------------未接听重发  start---------------------
        $('#sendFailedBtn').on('click', function() {
        	if(failedNumbers.length == 0){
        		new UserPrompt("没有未接听的留言需要重发！");
        		return;
        	}
        	for(var i=0;i<failedNumbers.length;i++){
        		reSend(failedNumbers[i]);
        	} 
        	failedNumbers = []; //重发后置空
        });
        //------------------未接听重发  end---------------------
	}
 })
	
